<template>
  <div style="padding: 10px">
    <el-form ref="elForm" :model="searchData" size="medium" label-width="100px">
      <el-row style="padding-bottom: 10px">
        <el-button
          type="primary"
          v-hasPermi="['business:tecPro:add']"
          size="mini"
          @click="addOrEdit(0)"
          >新增工艺</el-button
        >
        <el-button
          v-hasPermi="['business:tecPro:export']"
          type="danger"
          size="mini"
          @click="exportProduct()"
          >导出表格</el-button
        >
      </el-row>
    </el-form>

    <el-table
      :data="tableData"
      ref="dragTable"
      row-key="pkProTecPro"
      v-loading="tableLoading"
      style="width: 100%"
      border
    >
      <el-table-column width="50" align="center" type="index" label="序号">
      </el-table-column>
      <el-table-column
        prop="tecProName"
        label="工艺流程名称"
        width="180"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="craftNames" label="包含工序" align="center">
        <template slot-scope="scope">
          <el-tag
            size="medium"
            style="margin-right: 5px"
            v-for="(item, index) in scope.row.proCraftTecVoList"
            :key="index"
            >{{ item.craftName }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            slot="reference"
            @click="addOrEdit(scope.row)"
            type="text"
            size="small"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="removeCraft(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="dialogTitle + '工艺'"
      :visible.sync="addDialog"
      width="30%"
    >
      <el-form :model="edit" ref="edit" :rules="editRules" label-width="98px">
        <el-form-item label="工艺名称" prop="processFlowName">
          <el-input
            style="width: 200px"
            v-model="edit.tecProName"
            placeholder="请输入工艺名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="包含工序">
          <el-select
            v-model="edit.proCraftTecVoList"
            multiple
            style="width: 200px"
            placeholder="请选择包含工序"
          >
            <el-option
              v-for="item in craftInfList"
              :key="item.pkCraftInfo"
              :label="item.craftName"
              :value="item.pkCraftInfo"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-pagination
      style="margin-top: 10px"
      align="center"
      :hide-on-single-page="false"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 15, 20, 30]"
      :page-size="10"
      :current-page="searchData.pageNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </div>
</template>

<script>
import {
  getTecProListApi,
  removeCraftInfo,
  addTecProApi,
} from "@/api/product/product.js";
import { getAllCraftInfoListApi } from "@/api/craftInfo/craftInfo.js";
import Sortable from "sortablejs";

export default {
  components: {},
  computed: {},
  data() {
    return {
      tableLoading: true,
      tableData: [],
      total: 0,
      searchData: {
        pageNum: 1,
        pageSize: 10,
      },
      dialogTitle: "",
      addDialog: false,
      edit: {},
      // 表单校验
      editRules: {},
      craftInfList: [],
    };
  },
  created() {},
  async mounted() {
    await this.getCraftInfoPagingList();
    await this.getAllCraftInfoList();
  },
  methods: {
    // 查询工艺分页
    async getCraftInfoPagingList(page) {
      try {
        this.searchData.pageNum = page == null ? this.searchData.pageNum : page;
        const res = await getTecProListApi(this.searchData);
        if (res.data.list != null) {
          this.tableData = res.data.list;
          this.total = res.data.total;
        }
      } catch (error) {
      } finally {
        this.tableLoading = false;
      }
    },
    // 查询工序所有列表
    async getAllCraftInfoList() {
      const res = await getAllCraftInfoListApi(this.searchData);
      this.craftInfList = res.data;
    },
    //分页修改每页显示条数
    handleSizeChange(val) {
      this.searchData.pageSize = val;
      this.getCraftInfoPagingList();
    },
    //分页跳转页面
    handleCurrentChange(val) {
      this.searchData.pageNum = val;
      this.getCraftInfoPagingList();
    },
    clearForm() {
      this.searchData.craftName = "";
      this.searchData.craftSerialNum = "";
      this.getCraftInfoPagingList(1);
    },
    // 判断当前点击的是新增还是编辑
    async addOrEdit(row) {
      if (row === 0) {
        this.addDialog = true;
        this.dialogTitle = "新增";
        this.edit = {};
      } else {
        this.addDialog = true;
        this.dialogTitle = "编辑";
        let proCraftTecVoList = [];
        row.proCraftTecVoList.forEach((item) => {
          proCraftTecVoList.push(item.pkCraftInfo);
        });
        let deepRow = {
          pkProTecPro: row.pkProTecPro,
          tecProName: row.tecProName,
          proCraftTecVoList,
        };
        // 编辑需要回显数据
        this.edit = JSON.parse(JSON.stringify(deepRow)); //深拷贝
      }
    },
    onSubmit() {
      this.$refs["edit"].validate((valid) => {
        if (!valid) return;
        if (this.dialogTitle == "新增") {
          this.addCraft();
        } else {
          this.editTecPro();
        }
      });
    },
    // 新增工艺
    async addCraft() {
      const { tecProName, proCraftTecVoList, tecProRemark } = this.edit;
      let newProCraftTecVoList = [];
      this.craftInfList.forEach((item) => {
        proCraftTecVoList.forEach((child, index) => {
          if (item.pkCraftInfo == child) {
            newProCraftTecVoList.push({
              craftName: item.craftName,
              craftOrder: index,
              pkCraftInfo: item.pkCraftInfo,
              pkProCraftTec: "",
            });
          }
        });
      });
      let params = {
        proCraftTecVoList: newProCraftTecVoList,
        tecProName,
        tecProRemark,
      };
      const res = await addTecProApi(params);
      this.$message.success("新增成功");
      this.getCraftInfoPagingList(1);
      this.handleCancel();
    },

    // 修改工艺流程
    async editTecPro() {
      const { pkProTecPro, tecProName, proCraftTecVoList, tecProRemark } =
        this.edit;
      console.log(this.edit);
      let newProCraftTecVoList = [];
      this.craftInfList.forEach((item) => {
        proCraftTecVoList.forEach((child, index) => {
          if (item.pkCraftInfo == child) {
            newProCraftTecVoList.push({
              craftName: item.craftName,
              craftOrder: index + 1,
              pkCraftInfo: child,
              pkProCraftTec: "",
              // pkProTecPro: pkProTecPro,
            });
          }
        });
      });
      let params = {
        pkProTecPro,
        proCraftTecVoList: newProCraftTecVoList,
        tecProName,
        tecProRemark,
      };
      console.log(params);
      const { data: res } = await addTecProApi(params);
      console.log(res);
      this.$message.success("修改成功");
      this.getCraftInfoPagingList(1);
      this.handleCancel();
    },
    // 删除工艺
    async removeCraft(index, row) {
      console.log(row.pkProTecPro);
      const res = await removeCraftInfo(row.pkProTecPro);
      this.$message.success("移除成功");
      this.tableData.splice(index, 1);
    },

    // 取消清空弹窗操作
    handleCancel() {
      this.addDialog = false;
      this.$refs.edit.clearValidate(); // 取消需要清空表单校验（当前的表单用到了校验）
      this.edit = Object.assign(
        {},
        {
          // 清空表单数据
          craftName: "",
          craftNums: "",
          craftTotalPrice: "",
          craftRemark: "",
        }
      );
    },
    // 获取工序列表
    async getCraftInfoList() {
      const { data: res } = await getCraftInfo();
      console.log("工序", res);
      this.craftInfList = res;
    },
    // 导出表格
    exportProduct() {
      this.download(
        "/business/tecPro/export",
        {
          ...this.searchData,
        },
        `工艺${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style></style>
